<template>
  <div class='container'>
     <el-card style="margin-top: 10px;">
      <el-breadcrumb v-if="id" separator-class="el-icon-arrow-right">
      <!-- <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item> -->
      <el-breadcrumb-item>学科管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{name}}</el-breadcrumb-item>
      <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-row>
        <el-col :span="22">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="目录名称">
              <el-input
                v-model.trim="formInline.directoryName"
                placeholder="请输入目录名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formInline.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-button size="small" @click="clenFln">清除</el-button>
            <el-button type="primary" size="small" @click="search"
              >搜索</el-button>
               <el-link
              v-if="id"
              type="primary"
              icon="el-icon-back"
              @click="$router.push({ path: '/subjects/list' })"
              >返回学科</el-link
            >
          </el-form>
        </el-col>
        <el-col :span="2" >
          <el-button
            type="success"
            class="btn"
            size="small"
            icon="el-icon-edit"
            @click="hAdd"
            >新增目录</el-button
          >
        </el-col>
      </el-row>
        <template>
          <el-alert
         :title="`数据一共${total}条`"
         type="info"
         show-icon>
        </el-alert>
        </template>
        <el-table border :data="list" >
          <el-table-column label="序号"  type="index" width="50"/>
          <el-table-column label="所属学科" prop="subjectName"/>
          <el-table-column label="目录名称" prop="directoryName"/>
          <el-table-column label="创建者" prop="username"/>
          <el-table-column label="创建日期" prop="addDate">
            <template #default={row}>
              {{formatDate(row.addDate)}}
            </template>
          </el-table-column>
          <el-table-column label="面试题数量" prop="totals" />
          <el-table-column label="状态" prop="state" >
            <template #default={row}>
              {{hState(row.state)}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{row}">
               <el-button type="text" size="medium" @click="hDisabled(row)">{{row.state ===1 ? '启用':'禁用'}}</el-button>
               <el-button type="text" size="medium" :disabled="row.state === 1 ? false:true" @click="hEdit(row)">修改</el-button>
              <el-button type="text" size="medium" :disabled="row.state === 1 ? false:true" @click="hDel(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
          <el-pagination
            background
           :current-page="params.page"
           :page-sizes="[2, 5, 10,15, 20]"
           :page-size="params.pagesize"
           layout="prev, pager, next, sizes,jumper"
           :total="total"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           />
      </el-card>
      <el-dialog :visible.sync="showDialog" :title="isEdit ? '修改目录':'添加目录'" @closed="resetForm">
      <el-form ref="addForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item v-if="!id"  label="所属学科" prop="subjectID">
        <el-select v-model="formData.subjectID" style="width:80%" placeholder="请选择">
          <el-option v-for="item in subjectList " :key="item.id" :value="item.id" :label="item.subjectName" />
        </el-select>
        </el-form-item>
       <el-form-item label="目录名称" prop="directoryName">
        <el-input v-model="formData.directoryName" style="width:80%" placeholder="请输入目录名称" />
    </el-form-item>
  </el-form>

  <template #footer>
    <div style="text-align: right;">
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </template>
      </el-dialog>
  </div>
</template>

<script>
import { list, remove, add, update, changeState } from '@/api/hmmm/directorys.js'
import { subList } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      // isShowbianbao: false,
      id: this.$route.query.id,
      name: this.$route.query.name,
      isShow: true,
      subjectList: [],
      list: [],
      isEdit: false,
      formInline: {
        page: 1,
        pagesize: 10,
        directoryName: '',
        state: null
      },
      formData: {
        subjectName: '',
        directoryName: '',
        subjectID: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请输入学科名称', trigger: 'change' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      },
      showDialog: false,
      total: 0,
      params: {
        page: 1,
        pagesize: 10
      }
    }
  },
  created () {
    // 怎样区分跳转的页面和原来的页面,通过判断该页面的变量里卖弄有没有id的值.有就加载执行跳转页面的函数,没有就加载没有id页面的函数
    if (this.id) {
      this.loaddirectorysListBySubId()
    } else {
      this.loaddirectorysList()
      // this.loadsubjectsList()
    }
  },
  methods: {
    clenFln () {
      this.formInline = {
        page: 1,
        pagesize: 10,
        directoryName: '',
        state: null
      }
      this.loaddirectorysList()
    },
    formatDate (value) {
      return this.moment(value).format('YYYY-MM-DD HH:mm:ss')
    },
    async loaddirectorysListBySubId () {
      const res = await list({ subjectID: this.id, ...this.params })
      console.log(res, 'subdetail')
      this.$message.success('学科分类列表获取成功')
      this.list = res.data.items
      this.total = res.data.counts
    },
    search () {
      this.doSearch()
    },
    async doSearch () {
      const res = await list(this.formInline)
      console.log(res, 'directorylist')
      this.list = res.data.items
      this.total = res.data.counts
    },
    async hDisabled (row) {
      const res = await changeState({ id: row.id, state: row.state === 1 ? 0 : 1 })
      console.log(res, 'changeState')
      if (res.status !== 200) return this.$message.error('操作失败')
      this.$message.success('操作成功!')
      if (this.id) {
        this.loaddirectorysListBySubId()
      } else {
        this.loaddirectorysList()
      }
    },
    hState (id) {
      return id === 1 ? '已启用' : '已禁用'
    },
    resetForm () {
      this.$refs.addForm.resetFields()
      this.formData = {
        subjectName: '',
        directoryName: ''
      }
    },
    hSubmit () {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    async  doEdit () {
      try {
        const res = await update(this.formData)
        console.log(res)
        if (res.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功！')
        this.showDialog = false
        if (this.id) {
          this.loaddirectorysListBySubId()
        } else {
          this.loaddirectorysList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    async doAdd () {
      try {
        if (this.id) {
          const res = await add({ directoryName: this.formData.directoryName, subjectID: +this.id })
          console.log(res)
          if (res.status !== 200) return this.$message.error('添加失败')
          this.$message.success('添加成功！')
        } else {
          const res = await add(this.formData)
          console.log(res)
          if (res.status !== 200) return this.$message.error('添加失败')
          this.$message.success('添加成功！')
        }
        this.showDialog = false
        this.params.page = 1
        this.total++
        if (this.id) {
          this.loaddirectorysListBySubId()
        } else {
          this.loaddirectorysList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    hAdd () {
      this.isEdit = false
      this.showDialog = true
      this.loadsubjectsList()
    },
    hEdit (row) {
      this.isEdit = true
      this.showDialog = true
      this.formData = { ...row }
      this.loadsubjectsList()
    },
    hDel (row) {
      this.$confirm('你确定删除该目录吗?').then(async () => {
        const res = await remove(row)
        console.log(res, 'remove')
        if (this.list.length === 1) {
          this.params.page--
          if (this.params.page <= 0) {
            this.params.page = 1
          }
        }
        if (res.status === 200) {
          this.$message.success('删除成功！')
        }
        if (this.id) {
          this.loaddirectorysListBySubId()
        } else {
          this.loaddirectorysList()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    async loaddirectorysList () {
      try {
        const res = await list(this.params)
        console.log(res, 'directorysList')
        this.$message.success('加载目录列表成功')
        this.list = res.data.items
        this.total = res.data.counts
      } catch (err) {
        console.log(err)
        this.$message.error('加载目录列表数据失败')
      }
    },
    async loadsubjectsList () {
      try {
        const res = await subList({ page: 1, pagesize: 100 })
        console.log(res, 'subList')
        // this.$message.success('加载学科列表成功')
        this.subjectList = res.data.items
        // this.total = res.data.counts
      } catch (err) {
        console.log(err)
        this.$message.error('加载学科列表数据失败')
      }
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.params.page = 1
      this.params.pagesize = val
      this.loaddirectorysList(this.params)
    },

    async handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      if (this.formInline.directoryName === '' && this.formInline.state === '') {
        this.params.page = val
        this.loaddirectorysList(this.params)
      } else {
        this.formInline.page = val
        this.doSearch()
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin: 10px 15px;
  .el-breadcrumb {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
  }
  .btn {
    margin: 0px 10px;
  }
  .el-alert {
    margin-top: 10px;
    margin-bottom: 20px;
  }
  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }
  .el-link {
    float: right;
    margin-top: 10px;
    padding-left:20px ;
  }
}
</style>
